package com.neu.control;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.neu.daoimpl.UsersDaoImpl;
import com.neu.entity.LoginValidateInfo;
import com.neu.entity.TBUsers;
import com.neu.service.UsersService;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置相应的编码集
		response.setContentType("application/json;charset=utf-8");
		//  设置请求的编码集
		request.setCharacterEncoding("utf-8");
		//获取页面请求中的数据  用户名和密码
		String name = request.getParameter("username");
		String pass = request.getParameter("userpass");
		// 实例化 TBuser  传参
		TBUsers tb = new TBUsers(name, pass);
		//  调用服务层
		UsersService us = new UsersService(new UsersDaoImpl());
		boolean flag = false;
		Gson gs = new Gson();
		String info;
		try {
			flag = us.registerUser(tb);
			if(flag) {
				LoginValidateInfo lv = new LoginValidateInfo(1, "注册成功");
				info = gs.toJson(lv);
				response.getWriter().write(info);
			}else{
				LoginValidateInfo lv = new LoginValidateInfo(0, "注册失败");
				info = gs.toJson(lv);
				response.getWriter().write(info);
			}
			System.out.println(info);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
